package cn.jgy.dynamic.thread.pool.sdk.trigger.listener;

import cn.jgy.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import cn.jgy.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.jgy.dynamic.thread.pool.sdk.registry.IRegistry;
import com.alibaba.fastjson.JSON;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import java.util.List;


/**
* @Author: 蒋光耀
*@Version: 1.0
*@description: 实现动态线程池信息实时变更
* @Date:  2024-05-18 17:25
*/

public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolConfigEntity> {

    private Logger logger = LoggerFactory.getLogger(ThreadPoolConfigAdjustListener.class);

    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;

    public ThreadPoolConfigAdjustListener(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }

    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity threadPoolConfigEntity) {
        logger.info("动态线程池，调整线程池配置。线程池名称:{} 核心线程数:{} 最大线程数:{}", threadPoolConfigEntity.getThreadPoolName(), threadPoolConfigEntity.getPoolSize(), threadPoolConfigEntity.getMaximumPoolSize());
        dynamicThreadPoolService.threadPoolConfigUpdate(threadPoolConfigEntity);

        // 更新后上报最新数据

        List<ThreadPoolConfigEntity> threadPoolConfigEntities = dynamicThreadPoolService.threadPoolList();
        registry.reportThreadPoolList(threadPoolConfigEntities);

        ThreadPoolConfigEntity threadPoolConfigEntityCurrent = dynamicThreadPoolService.threadPoolByName(threadPoolConfigEntity.getThreadPoolName());
        registry.reportThreadPoolOne(threadPoolConfigEntity);
        logger.info("动态线程池，上报线程池配置：{}", JSON.toJSONString(threadPoolConfigEntity));
    }

}
